package com.chen.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.domain.SysRole;
import com.chen.domain.SysUser;
import com.chen.domain.SysUserRole;
import com.chen.dto.AdminUserDto;
import com.chen.mapper.SysUserMapper;
import com.chen.service.SysRoleService;
import com.chen.service.SysUserRoleService;
import com.chen.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private Snowflake snowflake = new Snowflake(1, 1);

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Page<SysUser> findList(Page<SysUser> page, String mobile, String fullname) {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(mobile)) {
            queryWrapper.like("mobile", mobile);
        }
        if (StringUtils.isNotBlank(fullname)) {
            queryWrapper.like("fullname", fullname);
        }

        queryWrapper.orderByDesc("last_update_time");
        Page<SysUser> userPage = page(page, queryWrapper);


        List<SysUser> records = userPage.getRecords();
        for (SysUser sysUser : records) {
            List<SysRole> userRole = sysRoleService.findUserRole(sysUser.getId().toString());
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < userRole.size(); i++) {
                stringBuffer.append(userRole.get(i).getId());
                if (i != userRole.size() - 1) {
                    stringBuffer.append(",");
                }

            }
            sysUser.setRole_strings(stringBuffer.toString());
        }


        return userPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUser sysUser) {
        long id = snowflake.nextId();
        sysUser.setId(id);
        //加密密码
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        //保存用户
        save(sysUser);

        //保存员工的角色关系

        saveUserRole(sysUser, id);

    }

    private void saveUserRole(SysUser sysUser, long id) {
        String[] roleIds = sysUser.getRole_strings().split(",");

        List<SysUserRole> roles = new ArrayList<>();

        for (String roleId : roleIds) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(Long.parseLong(roleId));
            sysUserRole.setUserId(id);
            roles.add(sysUserRole);
        }
        sysUserRoleService.saveBatch(roles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(SysUser sysUser) {
        //修改用户
        updateById(sysUser);

        //移除用户的角色
        sysUserRoleService.removeUserRoleByUserId(sysUser.getId());

        //保存角色
        saveUserRole(sysUser, sysUser.getId());


    }

    @Override
    public Map<Long, AdminUserDto> getAdminUser(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return null;
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        List<SysUser> list = this.list(queryWrapper);

        Map<Long, AdminUserDto> result = new HashMap<>();

        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
//        List<UserDto> userDtos = UserDtoMapper.INSTANCE.convert2ListDto(users);
        List<AdminUserDto> userDtos = list.stream().map(user -> {
            AdminUserDto userDto = new AdminUserDto();
            BeanUtils.copyProperties(user, userDto);
            return userDto;
        }).collect(Collectors.toList());
        for (int i = 0; i < userDtos.size(); i++) {
            result.put(userDtos.get(i).getId(), userDtos.get(i));
        }
        return result;
    }
}
